"use client";

/**
 * ConvexProviderWithClerk：https://docs.convex.dev/api/modules/react_clerk
 * ClerkProvider：用于提供 Clerk用户管理 的认证上下文
 * useAuth：用于访问 Clerk 的认证状态和功能的hooks
 */

import { ClerkProvider, useAuth } from "@clerk/nextjs";
import { ConvexProviderWithClerk } from "convex/react-clerk";
import { AuthLoading, Authenticated, ConvexReactClient } from "convex/react";
import { Loading } from "@/components/auth/loading";

interface ConvexClientProviderProps {
  children: React.ReactNode;
}

/**
 * @description convexUrl 部署的url
 * @convex 通过 ConvexReactClient 创建与 Convex 服务的 WebSocket 连接
 */
const convexUrl = process.env.NEXT_PUBLIC_CONVEX_URL!; // ！表示不是未定义的
const convex = new ConvexReactClient(convexUrl);

export const ConvexClientProvider = ({
  children,
}: ConvexClientProviderProps) => {
  return (
    <ClerkProvider>
      {/* ConvexProviderWithClerk 是Convex和Clerk集成的一个提供器组件，它允许你的应用程序与 Convex 的后端服务进行通信，并且结合 Clerk 的身份验证功能 */}
      <ConvexProviderWithClerk useAuth={useAuth} client={convex}>
        {/* 认证成功后的内容 */}
        <Authenticated>{children}</Authenticated>
        <AuthLoading>
          {/* 在加载期间显示的内容 */}
          <Loading></Loading>
        </AuthLoading>
      </ConvexProviderWithClerk>
    </ClerkProvider>
  );
};
